package com.app.baselibrary.utils

import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import java.io.*
import java.text.SimpleDateFormat


object ImageUtil {

    /**
     * 保存图片路径
     */
    private val IMAGE_PATH = "Pictures/BK"

    fun getActivityBitmap(context: Context): Bitmap? {
        var bitmap: Bitmap? = null
        return bitmap
    }

    fun getBitmap(context: Context, vectorDrawableId: Int): Bitmap? {
        var bitmap: Bitmap? = null
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            val vectorDrawable = context.getDrawable(vectorDrawableId)
            bitmap = Bitmap.createBitmap(
                vectorDrawable!!.intrinsicWidth,
                vectorDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888
            )

            val canvas = Canvas(bitmap!!)
            vectorDrawable.setBounds(0, 0, canvas.width, canvas.height)
            vectorDrawable.draw(canvas)
        } else {
            bitmap = BitmapFactory.decodeResource(context.resources, vectorDrawableId)
        }
        return bitmap
    }

    /**
     * 对View进行截图
     */
    fun getViewBitmap(view: View):Bitmap{
        //使控件可以进行缓存
        view.isDrawingCacheEnabled = true
        //获取缓存的 Bitmap
        var drawingCache = view.drawingCache
        //复制获取的 Bitmap
        drawingCache = Bitmap.createBitmap(drawingCache)
        //关闭视图的缓存
        view.isDrawingCacheEnabled = false
        return  drawingCache
    }

    //全屏显示图片
    fun getShareBitmap(context: Context, vectorDrawableId: Int): Bitmap? {
        var bitmap: Bitmap? = null
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            //获取窗体的宽高,对不同分辨率的手机进行适配
            val manager = context
                .getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val display = manager.defaultDisplay
            val width = display.width
            val height = display.height
            val vectorDrawable =context.getDrawable(vectorDrawableId)
            bitmap = Bitmap.createBitmap(
                width,
                height, Bitmap.Config.ARGB_8888
            )
            val canvas = Canvas(bitmap!!)
            vectorDrawable!!.setBounds(0, 0, canvas.width, canvas.height)
            vectorDrawable.draw(canvas)
        } else {
            bitmap = BitmapFactory.decodeResource(context.resources, vectorDrawableId)
        }
        return bitmap
    }

    //保存bitmap
    fun savaBitmap(context: Context, bitmap: Bitmap) {
        var out: FileOutputStream? = null
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED)
        // 判断是否可以对SDcard进行操作
        {    // 获取SDCard指定目录下
            val sdCardDir = IMAGE_PATH
            val dirFile = File(sdCardDir)  //目录转化成文件夹
            if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                dirFile.mkdirs()
            }                          //文件夹有啦，就可以保存图片啦
            val file = File(
                sdCardDir,
                System.currentTimeMillis().toString() + ".jpg"
            )// 在SDcard的目录下创建图片文,以当前时间为其命名

            try {
                out = FileOutputStream(file)
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            }

            try {
                out!!.flush()
                out.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }

            context.sendBroadcast(
                Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.fromFile(File(file.path))
                )
            )
        }
    }

    fun savePictures(
        context: Context,
        bitmap: Bitmap
    ): String? {
        //拍照存放路径
        val sdChildPath: String = IMAGE_PATH
        //为了适配Android Q版本以下
        val fileDir =
            File(Environment.getExternalStorageDirectory(), sdChildPath)
        if (!fileDir.exists()) {
            fileDir.mkdir()
        }
        //        String fileName = "IMG_" + System.currentTimeMillis();

        val sf = SimpleDateFormat("yyyyMMdd_HHmmss")
        val fileName = "IMG_" + sf.format(System.currentTimeMillis())
        val filePath = fileDir.absolutePath + "/" + fileName + ".jpg"
        //设置保存参数到ContentValues中
        val contentValues = ContentValues()
        //设置文件名
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
        //兼容Android Q和以下版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { //android Q中不再使用DATA字段，而用RELATIVE_PATH代替
            //RELATIVE_PATH是相对路径不是绝对路径
            //DCIM是系统文件夹，关于系统文件夹可以到系统自带的文件管理器中查看，不可以写没存在的名字
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, sdChildPath)
        } else { //Android Q以下版本
            contentValues.put(MediaStore.Images.Media.DATA, filePath)
        }
        contentValues.put(MediaStore.Images.Media.DESCRIPTION, fileName)
        //设置文件类型
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG")
        //执行insert操作，向系统文件夹中添加文件
        //EXTERNAL_CONTENT_URI代表外部存储器，该值不变
        val uri = context.contentResolver
            .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        val outputStream: OutputStream?
        try {
            outputStream = context.contentResolver.openOutputStream(uri!!)
            //进行压缩
            if (outputStream != null) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
            }
            outputStream?.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        val realPathFromUri: String? = getRealPathFromURI(context, uri)
        // 最后通知图库更新
        MediaScannerConnection.scanFile(
            context,
            arrayOf(realPathFromUri),
            null,
            null
        )
        return realPathFromUri
    }



    fun getRealPathFromURI(
        context: Context,
        contentURI: Uri?
    ): String? {
        var result: String? = ""
        contentURI?.let {
            val cursor: Cursor? = context.contentResolver.query(
                contentURI, arrayOf(MediaStore.Images.ImageColumns.DATA),  //
                null, null, null
            )
            if (cursor == null) result = contentURI.path else {
                cursor.moveToFirst()
                val index: Int = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
                result = cursor.getString(index)
                cursor.close()
            }
        }

        return result
    }

    //首先传入两张图片
    private fun mergeThumbnailBitmap(firstBitmap: Bitmap, secondBitmap: Bitmap): Bitmap? {
        //以其中一张图片的大小作为画布的大小，或者也可以自己自定义
        val bitmap = Bitmap.createBitmap(
            firstBitmap.width, firstBitmap
                .height, firstBitmap.config
        )
        //生成画布
        val canvas = Canvas(bitmap)
        //因为我传入的secondBitmap的大小是不固定的，所以我要将传来的secondBitmap调整到和画布一样的大小
        val w = firstBitmap.width.toFloat()
        val h = firstBitmap.height.toFloat()
        val sw = secondBitmap.width.toFloat()
        val sh = secondBitmap.height.toFloat()
        val m = Matrix()
        //确定secondBitmap大小比例
        m.setScale(w / sw, h / sh)
        m.setTranslate((w - sw) / 2, (h - sh) / 2-sh/5)
        //        Paint paint = new Paint();
//        //给画笔设定透明值，想将哪个图片进行透明化，就将画笔用到那张图片上
//        paint.setAlpha(150);
        canvas.drawBitmap(firstBitmap, 0f, 0f, null)
        //        canvas.drawBitmap(secondBitmap, m, paint);
        canvas.drawBitmap(secondBitmap, m, null)
        return bitmap
    }


    fun saveToPictures(
        context: Context,
        bitmap: Bitmap,
        name: String
    ): String? {

        //拍照存放路径
        val sdChildPath: String = IMAGE_PATH
        //为了适配Android Q版本以下
        val fileDir =
            File(Environment.getExternalStorageDirectory(), sdChildPath)
        if (!fileDir.exists()) {
            fileDir.mkdir()
        }
        val filePath = fileDir.absolutePath + "/" + name + ".jpg"
        //设置保存参数到ContentValues中
        val contentValues = ContentValues()
        //设置文件名
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, name)
        //兼容Android Q和以下版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { //android Q中不再使用DATA字段，而用RELATIVE_PATH代替
            //RELATIVE_PATH是相对路径不是绝对路径
            //DCIM是系统文件夹，关于系统文件夹可以到系统自带的文件管理器中查看，不可以写没存在的名字
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, sdChildPath)
        }
        else { //Android Q以下版本
            contentValues.put(MediaStore.Images.Media.DATA, filePath)
        }
        contentValues.put(MediaStore.Images.Media.DESCRIPTION, name)
        //设置文件类型
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG")
        //执行insert操作，向系统文件夹中添加文件
        //EXTERNAL_CONTENT_URI代表外部存储器，该值不变
        val uri = context.contentResolver
            .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        val outputStream: OutputStream?
        try {
            outputStream = context.contentResolver.openOutputStream(uri!!)
            if (outputStream != null) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
            }
            outputStream?.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        val realPathFromUri: String? = getRealPathFromURI(context, uri)
        // 最后通知图库更新
        MediaScannerConnection.scanFile(
            context,
            arrayOf(realPathFromUri),
            null,
            null
        )
        return realPathFromUri
    }

    //保存bitmap
    fun saveImageToGallery(context: Context,bmp: Bitmap, name: String): String? {
        //生成路径
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED){
            //生成路径
            val root =Environment.getExternalStorageDirectory().absolutePath
            val dirName = IMAGE_PATH
            val appDir = File(root, dirName)
            if (!appDir.exists()) {
                appDir.mkdirs()
            }
            val fileName = "$name.jpg"
            //获取文件
            val file = File(appDir, fileName)
            var fos: FileOutputStream? = null
            try {
                fos = FileOutputStream(file)
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                fos.flush()
                //通知系统相册刷新
                context.sendBroadcast(
                    Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.fromFile(File(file.path))
                    )
                )
                return file.path
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                try {
                    fos?.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        return "-1"
    }

    fun deletLoaclImage(context: Context, filePath: String){
        val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val mContentResolver: ContentResolver = context.contentResolver
        val where = MediaStore.Images.Media.DATA + "='" + filePath + "'"
        //删除图片
        mContentResolver.delete(uri, where, null)
        //更新图库
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            MediaScannerConnection.scanFile(
                context,
                arrayOf(filePath),
                null,
                null
            )
        } else {
            context.sendBroadcast(
                Intent(
                    Intent.ACTION_MEDIA_MOUNTED,
                    Uri.parse("file://" + Environment.getExternalStorageDirectory())
                )
            )
        }
    }
    fun deletePicture(
        localPath: String?,
        context: Context
    ) {
        if (!TextUtils.isEmpty(localPath)) {
            val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            val contentResolver = context.contentResolver
            val url = MediaStore.Images.Media.DATA + "=?"
            val deleteRows =
                contentResolver.delete(uri, url, arrayOf(localPath))
            if (deleteRows == 0) { //当生成图片时没有通知(插入到）媒体数据库，那么在图库里面看不到该图片，而且使用contentResolver.delete方法会返回0，此时使用file.delete方法删除文件
                val file = File(localPath)
                if (file.exists()) {
                    file.delete()
                }
            }
        }
    }

    //判断文件是否存在
    fun fileIsExists(strFile: String?): Boolean {
        try {
            val f = File(strFile)
            if (!f.exists()) {
                return false
            }
        } catch (e: java.lang.Exception) {
            return false
        }
        return true
    }

    /**
     * 裁剪后的地址
     */
    fun getCuttingImageFilePath(mContext:Context): String? {
//        val path: String = Environment.getExternalStorageDirectory().toString() + "/LBJ/"
        val path: String =mContext.getExternalFilesDir(null)!!.absolutePath
        val file = File(path)
        return if (file.mkdirs()) {
            path
        } else path
    }
}